<template>
    <div>
        <div class="orderList" style="">
            <h3>订单导出</h3>
            运单状态：<el-select style="width:15%;margin-bottom:20px;margin-right:20px" v-model="logistic_status" @change="handleLogistic()" placeholder="选择运单状态">
                <el-option v-for="item in option" :key="item.id" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
            支付状态：<el-select style="width:15%;margin-bottom:20px; margin-right:20px;" v-model="order_status" @change="handleOrder()" placeholder="选择支付状态">
                <el-option v-for="item in option1" :key="item.id" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
        
            选择品牌：<el-select style="width:15%;margin-bottom:20px; margin-right:20px;" v-model="form.brandId" @change="handleBrandId()" placeholder="选择品牌">
                <el-option v-for="item in brandArr" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
            
            订单类型：<el-select style="width:15%;margin-bottom:20px;margin-right:20px;"  v-model="orderType" @change="handleType()" placeholder="选择订单类型">
                <el-option v-for="item in option3" :key="item.id" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
            <template style="margin-bottom:20px;">
                <div class="block el-select" style="margin-bottom:20px;">
                   选择日期：<el-date-picker v-model="searchTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" @change="handlChangeOrderData">
                    </el-date-picker>
                    <el-button type="primary" @click="searchOrder">搜索订单</el-button>
                    <!-- <el-button type="primary" @click="exportOrderTypeExcel()">导出礼包订单</el-button> -->
                </div>
            </template>
            <template>
                <el-button v-if='orderData.length>0 || orderTypeArray != null' style="float:right" type="primary" @click="exportTable()">导出Excel</el-button>
                <!-- <el-button style="float:right" type="primary" @click="exportTable()">导出Excel</el-button> -->
            </template>
            <div v-loading="loading" style="min-height:400px" v-if="(this.orderType == 1 || this.orderType == '') && this.orderArray != null ">
                <div v-for='item in orderArray' :key="item.id">
                    <template>
                        <h2 style="padding:20px 10px;color:red;font-size:24px">{{item.brandName}} </h2>
                        <el-table  ref="multipleTable" :data="item.activityList" style="width: 100%">
                            <el-table-column fixed prop="orderId" label="订单编号" width="200">
                            </el-table-column>
                            <el-table-column  prop="transactionId" label="微信流水号" width="260">
                            </el-table-column>
                            <el-table-column  prop="tradeType" label="下单方式" width="150">
                                <template slot-scope="scope">{{scope.row.tradeType == 'JSAPI' ? '小程序' : (scope.row.tradeType == 'APP' ? 'APP' : '')}}</template>
                            </el-table-column>
                            <el-table-column  prop="couponAmount" label="优惠券金额" width="150">
                            </el-table-column>
                            <el-table-column  prop="totalFee" label="实际支付金额" width="150">
                            </el-table-column>
                            <el-table-column  prop="postage" label="运费" width="120">
                            </el-table-column>
                            <el-table-column prop="orderStatus" label="订单状态" width="120">
                                <template slot-scope="scope">{{scope.row.orderStatus == 'S' ? '支付成功':(scope.row.orderStatus == 'W' ? '待支付':(scope.row.orderStatus == 'F' ? '支付失败' :(scope.row.orderStatus == 'RW' ? '申请退款' :(scope.row.orderStatus == 'RU' ? '退款中':(scope.row.orderStatus == 'RS'?'已退款':(scope.row.orderStatus == 'C' ?'已完成' :(scope.row.orderStatus == 'Q' ?'已取消':(scope.row.orderStatus == 'RF' ? '退款失败' : (scope.row.orderStatus == 'AU' ? '申请退款中' : '')))))))))}}</template>
                            </el-table-column>
                            <el-table-column prop="logisticStatus" label="运单状态" width="120">
                                <template slot-scope="scope">{{scope.row.logisticStatus == 'LU' ? '已发货':(scope.row.logisticStatus == 'LW'?'待发货' : (scope.row.logisticStatus == 'LP' ? '部分发货' : '已收货')) }}</template>
                            </el-table-column>
                            <el-table-column prop="contacts" label="联系人姓名" width="150">
                            </el-table-column>
                            <el-table-column prop="phone" label="联系人电话" width="150">
                            </el-table-column>
                            <el-table-column  prop="address" label="收货地址" width="240">
                            </el-table-column>
                            <el-table-column fixed="right" prop="createTime" label="下单时间" width="180">
                                <template slot-scope="scope">{{ $formate(scope.row.createTime,'yyyy-MM-dd hh:mm:ss') }}</template>
                            </el-table-column>
                        </el-table>
                    </template>
                </div>
            </div>
            <!-- 礼包订单 -->
            <div v-loading="loading" style="min-height:400px" v-else>
                <div>
                    <template v-if="this.orderTypeArray!=null">
                        <h2 v-if="this.orderType == 2" style="padding:20px 10px;color:red;font-size:24px">{{'礼包订单'}} </h2>
                        <h2 v-if="this.orderType == 3" style="padding:20px 10px;color:red;font-size:24px">{{'会员订单'}} </h2>
                        <el-table  ref="multipleTable" :data="orderTypeArray" style="width: 100%">
                            <el-table-column fixed prop="orderId" label="订单编号" width="200">
                            </el-table-column>
                            <el-table-column  prop="transactionId" label="微信流水号" width="260">
                            </el-table-column>
                            <el-table-column  prop="goodsName" label="礼包名称" width="240">
                            </el-table-column>
                            <el-table-column prop="orderStatus" label="订单状态" width="100">
                                <template slot-scope="scope">
                                    {{scope.row.orderStatus}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="logisticStatus" label="运单状态" width="100">
                                <template slot-scope="scope">
                                    {{scope.row.logisticStatus}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="contacts" label="联系人姓名" width="120">
                            </el-table-column>
                            <el-table-column prop="phone" label="联系人电话" width="150">
                            </el-table-column>
                            <el-table-column  prop="address" label="收货地址" width="240">
                            </el-table-column>
                            <el-table-column  fixed="right" prop="createTime" label="下单时间" width="160">
                                <template slot-scope="scope">{{ $formate(scope.row.createTime,'yyyy-MM-dd hh:mm:ss') }}</template>
                            </el-table-column>
                        </el-table>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import leftBar from "../commonComponents/leftBar.vue";
import {getActivityOrderData, activityList, allActivityList, getBrandList} from "../../data/postData.js";
export default {
    components: {
        leftBar
    },
    data() {
        return {
            user: JSON.parse(localStorage.getItem("ddaigoUser")),
            form: {
                activityId: "",
                brandId: ''
            },
            orderTypeArray:null,
            loading: false,
            activityArr: [],
            orderNo: "",
            data: null,
            orderData: [],
            logistic_status:'',
            order_status: '',
            orderType:'',
            page: 1,
            size: 5,
            total: "",
            searchTime: [],
            startTime: "",
            endTime: "",
            excel: "表格",
            goodsItem: null,
            orderArray: null,
            brandArr:null,//品牌
            option: [
                {
                    id: 0,
                    value: "",
                    label: "全部订单"
                },
                {
                    id: 1,
                    value: "LU",
                    label: "已发货"
                },
                {
                    id: 2,
                    value: "LW",
                    label: "待发货"
                },
                {
                    id: 3,
                    value: "LS",
                    label: "已收货"
                },
                {
                    id: 4,
                    value: "LP",
                    label: "部分发货"
                }
            ],
            option1: [
                {
                    id: 0,
                    value: "",
                    label: "全部订单"
                },
                {
                    id: 1,
                    value: 'S',
                    label: "支付成功"
                },
                {
                    id: 2,
                    value: "W",
                    label: "待支付"
                },
                {
                    id: 3,
                    value: "F",
                    label: "支付失败"
                },
                {
                    id: 4,
                    value: "RW",
                    label: "申请退款"
                },
                {
                    id: 5,
                    value: "RU",
                    label: "退款中"
                },
                {
                    id: 6,
                    value: "RS",
                    label: "已退款"
                },
                {
                    id: 7,
                    value: "C",
                    label: "已完成"
                },
                {
                    id: 8,
                    value: "Q",
                    label: "已取消"
                },
                {
                    id: 9,
                    value: "AU",
                    label: "退款审核中"
                },
                {
                    id: 10,
                    value: "RF",
                    label: "退款失败"
                }
            ],
            option3: [
                {
                    id: "0",
                    value: "",
                    label: "全部订单"
                },
                {
                    id: "1",
                    value: "1",
                    label: "商品订单"
                },
                {
                    id: "2",
                    value: "2",
                    label: "礼包订单"
                },
                {
                    id: "3",
                    value: "3",
                    label: "会员订单"
                }
            ]
        };
    },
    mounted() {
        if(this.searchTime.length < 1){
            this.searchTime[0] = new Date(new Date(new Date().toLocaleDateString()).getTime()-6*24*60*60*1000)
            this.searchTime[1] = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1)
        }
        let {
            orderStatus,
            logisticStatus,
            orderType,
            brandId,
          
        } = this.$store.state.orderExport;
        this.order_status = orderStatus || '';
        this.logistic_status = logisticStatus || '';
        this.orderType = '' + orderType || "";
        this.form.brandId = brandId || '';
        var params = {
            "data":{
                'page': 1,
                'size': 100000000
            }
        }
        this.$fetch.post(getBrandList, params).then(res => {
            var brandList = []
            res.data.forEach(item => {
                brandList.push({
                    id: item.id,
                    name: item.name
                })
                
            })
            this.brandArr = brandList
            this.brandArr.unshift({
                    id: '',
                    name: '全部'
                })
        }).catch(err => {
            this.$message({
                message: err.message,
                type: 'error',
                duration: 1000
            })
        })
    },
    methods: {
        handlChangeOrderData() {
            // if(this.searchTime[0]&& this.searchTime[0] != '' && this.searchTime[1] && this.searchTime[1] !=''){
            //     this.getOrderData()
            // }
        },
        getOrderData() {
            this.loading = true;
            let paramso = {
                data: {
                    orderStatus: this.order_status,
                    logisticStatus: this.logistic_status,
                   // activityId: this.form.activityId,
                    brandId: this.form.brandId,
                    startTime: this.startTime,
                    endTime: this.endTime,
                    orderType:this.orderType
                }
            };

            this.$fetch.post(getActivityOrderData, paramso).then(res => {
                    this.loading = false;
                    if(this.orderType == 1 || this.orderType == '' ){
                        this.orderArray = res.data;
                    }else{
                        this.orderTypeArray = res.data.activityList
                    }
                    if (res.data.length < 1) {
                        this.$message({
                            message: "暂无订单",
                            type: "success"
                        });
                    }
                    var arr2=[];
                    //搜索非礼包订单
                    if(this.orderType == 1 || this.orderType == ''){

                        let arr = [];
                        this.orderArray.forEach((item, i) => {
                            arr = arr.concat(item.activityList);
                        });
                        console.log(arr,'arr')
                        arr.forEach((xxo, m) => {
                            if(xxo.orderList){
                                arr2 = arr2.concat(xxo.orderList);
                            }else{
                                arr2 = arr2.concat(xxo);
                            }
                        });
                    }else{
                        arr2 = this.orderTypeArray
                    }
                      console.log(arr2, '-------arr3------')
                    arr2.forEach(xxp => {
                        xxp.address = (xxp.address && xxp.address != "null" && xxp.address != undefined && xxp.address != null && xxp.address != '') ? xxp.address : "";
                        if (xxp.address != '') {
                            xxp.address = xxp.address.trim();
                            xxp.address1 = xxp.address.split(" ");
                            if (xxp.address1.length < 4) {
                                xxp.province = xxp.address1[0];
                                xxp.city = xxp.address1[1];
                                xxp.area = xxp.address1[2];
                                xxp.address2 = xxp.address1.slice(3);
                            } else {
                                xxp.province = xxp.address1[0];
                                xxp.city = xxp.address1[1];
                                xxp.area = xxp.address1[2];
                                xxp.address2 = xxp.address1.slice(3);
                            }
                        } else {
                            xxp.province = "";
                            xxp.city = "";
                            xxp.area = "";
                            xxp.address2 = "";
                        }
                        xxp.createTime = this.$formate(xxp.createTime, "yyyy-MM-dd hh:mm:ss");
                        xxp.orderStatus= xxp.orderStatus == 'S' ? '支付成功' : (xxp.orderStatus == 'W' ? '待支付' : (xxp.orderStatus == 'F' ? '支付失败' : (xxp.orderStatus == 'Q' ? '已取消' : (xxp.orderStatus == 'RW' ? '申请退款' : (xxp.orderStatus == 'RU' ? '退款中' : (xxp.orderStatus == 'RS' ? '已退款' : (xxp.orderStatus == 'C' ? '已完成' : (xxp.orderStatus == 'RF' ? '退款失败' : (xxp.orderStatus == 'AU' ? '申请退款中' : '')))))))))
                        xxp.logisticStatus= xxp.logisticStatus== 'LU' ? '已发货' : (xxp.logisticStatus== 'LW' ? '待发货' : (xxp.logisticStatus== 'LS' ? '已收货' : (xxp.logisticStatus== 'LP' ? '部分发货' : '')))
                        xxp.isOffline = (xxp.isOffline == 0 || xxp.isOffline == null || xxp.isOffline == 'null') ? '线上' : '线下'
                        xxp.tradeType = xxp.tradeType == 'JSAPI' ? '小程序' : (xxp.tradeType == 'APP' ? 'APP' : '')
                        console.log('------------',xxp)
                    });
                    var arr3 = [];
                    // for(var i = 0; i<arr2.length; i++){
                    //     filter(['activityName','orderId'],i)
                    // }
                    console.log(arr2, '-------arr2------')
                    this.orderData = arr2;
                    //this.total = arr.length;
                    function filter(name, j) {
                        name.forEach(val => {
                            if (arr3.indexOf(arr2[j][val]) >= 0) {
                                arr2[j][val] = "";
                            } else {
                                arr3.push(arr2[j][val]);
                            }
                        });
                    }
                 //   this.total = arr.length;
                }).catch(err => {
                    this.$message({
                        message: err.message,
                        type: "error",
                        duration: 1000
                    })
                     this.loading = false;
                });
            // }
        },

        // 导出表格
        exportTable() {
            if(this.orderType != 2 && this.orderType != 3){
                if (this.orderArray.length == 1) {
                    this.excel = this.orderData[0].brandName + "订单" + this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss");
                } else {
                    this.excel = "所有品牌订单" + this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss");
                }
            }else if(this.orderType == 2){
                this.excel = "礼包订单" + this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss");
            }else{
               this.excel = "会员订单" + this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss"); 
            }
            var orderData1 = this.orderData;
            console.log(orderData1, '--------------')
            var str = "品牌名称, 订单编号, 微信流水号, 下单方式, 支付状态, 发货状态, 下单时间, 联系人, 联系人电话, 省, 市, 县城／区, 详细地址, 商品名称, 商品颜色, 商品编码, 商品条码, 线上/线下, 商品数量, 商品原价, 商品现价, 优惠券金额, 运费, 实际支付金额, 商品颜色, 商品图片, 尺码 " + "\n";
            //str+='\uFEFF';
            //增加\t为了不让表格显示科学计数法或者其他格式
            for (var i = 0; i < orderData1.length; i++) {
                str += '"' + orderData1[i]["brandName"] + '"' + ",";
                str += orderData1[i]["orderId"] + "\t" + ",";
                str += orderData1[i]["transactionId"] + "\t" + ",";
                str += '"' + orderData1[i]["tradeType"] + '"' + ",";
                str += '"' + orderData1[i]["orderStatus"] + '"' + ",";
                str += '"' + orderData1[i]["logisticStatus"] + '"' + ",";
                str += '"' + orderData1[i]["createTime"] + '"' + ",";
                str += '"' + orderData1[i]["contacts"] + "\t" + '"' + ",";
                str += '"' + orderData1[i]["phone"] + '"' + ",";
                str += '"' + orderData1[i]["province"] + '"' + ",";
                str += '"' + orderData1[i]["city"] + '"' + ",";
                str += '"' + orderData1[i]["area"] + '"' + ",";
                str += '"' + orderData1[i]["address2"] + '"' + ",";
                str += '"' + orderData1[i]["goodsName"] + "\t" + '"' + ",";
                str += '"' + orderData1[i]["goodsColor"] + "\t" + '"' + ",";
                str += '"' + orderData1[i]["goodsCode"] + "\t" + '"' + ",";
                str += '"' + orderData1[i]["barCode"] + "\t" + '"' + ",";
                str += '"' + orderData1[i]["isOffline"] + "\t" + '"' + ",";
                str += +orderData1[i]["goodsNum"] + ",";
                str += +orderData1[i]["originalPrice"] + ",";
                str += +orderData1[i]["goodsPrice"] + ",";
                str += +orderData1[i]["couponAmount"] + ",";
                str += +orderData1[i]["postage"] + ",";
                str += +orderData1[i]["totalFee"] + ",";
                str += '"' + orderData1[i]["goodsColor"] + '"' + ",";
                str += '"' + orderData1[i]["goodsPic"] + '"' + ",";
               
                str += '"' + orderData1[i]["specsName"] + '"' + ",";
                str += "\n";
            }
            //encodeURIComponent解决中文乱码
            var uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);

            function requiredFeaturesSupported() {
                return BlobConstructor() && msSaveOrOpenBlobSupported();
            }

            function BlobConstructor() {
                if (!window.Blob) {
                    return false;
                } // if

                return true;
            } // BlobConstructor

            function msSaveOrOpenBlobSupported() {
                if (!window.navigator.msSaveOrOpenBlob) {
                    return false;
                } // if

                return true;
            } // msSaveOrOpenBlobSupported

            //通过创建a标签实现
            var link = document.createElement("a");
            link.href = uri;

            if (requiredFeaturesSupported()) {
                var blobObject = new Blob([str], { type: "text/csv;charset=utf-8"});
                window.navigator.msSaveOrOpenBlob(blobObject, this.excel + ".csv");
            } else {
                //对下载的文件命名
                link.download = this.excel + ".csv";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        },
        searchOrder() {
            if (this.searchTime.length > 0) {
                this.startTime = this.$formate(new Date(this.searchTime[0]).getTime(), "yyyy-MM-dd hh:mm:ss");
                this.endTime = this.$formate(new Date(this.searchTime[1]).getTime(), "yyyy-MM-dd hh:mm:ss");
                if((Math.floor(+new Date(this.searchTime[1]).getTime() - new Date(this.searchTime[0]).getTime())/1000/60/60/24) > 30){
                    this.$message({
                        message: '允许最大时间范围为30天',
                        type: 'error',
                        duration: 1000
                    })
                }else{
                    this.getOrderData();
                }
            } else {
                this.startTime = this.$formate(new Date(new Date(new Date().toLocaleDateString()).getTime()-30*24*60*60*1000).getTime(), "yyyy-MM-dd hh:mm:ss");
                this.endTime = this.$formate(new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1).getTime(), "yyyy-MM-dd hh:mm:ss");
                this.getOrderData();
            }
        },
        handleLogistic(){
            this.$store.dispatch("saveOrderExportLogisticStatus", this.logistic_status);
        },
        handleOrder(){
            this.$store.dispatch("saveOrderExportStatus", this.order_status);
        },
        handleType(){
            this.$store.dispatch("saveOrderExportOrderType", this.orderType);
        },
        handleBrandId(){
            this.$store.dispatch("saveOrderBrandId", this.form.brandId);
        },
        handleActivity(){
            this.$store.dispatch("saveOrderActivityId", this.form.activityId);
        }

    }
};
</script>
<style scoped lang="less">
.orderList {
    width: calc(~"100% - 250px");
    margin-top: 66px;
    margin-left: 230px;
    float: left;
    h3 {
        margin: 20px 0px;
        //font-size:24px;
    }
    .input {
        width: 300px;
    }
}
.pagination {
    display: flex;
    justify-content: center;
    margin: 20px 0;
}
</style>
